(function(){
    angular.module('app').controller("dspAgentMangeCtrl",function($scope,proxy){
        $scope.permission = PERMISSION;
        $scope.profits = {
            type: 1
        }
        $scope.pwd = {};
        $scope.encodeURI = encodeURI;
        $scope.sTime = getNowFormatDate() + " 00:00:00";
        $scope.eTime = getNowFormatDate() + " 23:59:59";
        $scope.filter = {};
        $scope.search = function(v){
            $scope.filter.name = v;
            getList();
        }
        $scope.chooseDate = function (start, end) {
            $scope.sTime = start;
            $scope.eTime = end;
            getList();
        }
        // 显示利润设置弹框
        $scope.showProfits = function(item) {
            $scope.profits.value = (item.premium * 100).toFixed(2);
            $scope.profits.id = item.id;
            layer.open({
                type: 1,
                title: "利润设置",
                content: $('.profits'),
                area:["295px","250px"]
            })
        }
        // 设置广告公司利润率
        $scope.profitSet = function() {
            var premium = ($scope.profits.value /100).toFixed(4),
                id = $scope.profits.id;
            if($scope.profits.value == "" || isNaN(premium) || premium < 0) return layer.msg("利润必须为大于等于0的数字！")
            if(premium > $scope.premiumMax) return layer.msg("利润设置不能超过"+($scope.premiumMax*100)+"%")
            var data = {
                id: id,
                premium: premium
            };
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/finance/profit/set',
                load: true,
                data: data,
                success: function(res){
                    layer.closeAll();
                    getList();
                }
            })
        }
        // 显示转账弹框
        $scope.showMask = function(type,item) {
            $scope.financeType = type;
            $scope.advertiserID = item.id;
            $scope.agentName = item.loginName;
            $scope.balance = item.balance;
            layer.open({
                type: 1,
                title: type == "putin" ?"充值":"转出资金",
                content: $('.transfer'),
                area:["580px","330px"]
            })
        }
        // 转账
        $scope.transfer = function() {
            var str,url;
            if($scope.financeType == "putin") {
                str = "充值";
                url = STATIC_URL.domian+'/dsp/admin/agencyfinance/deposit';
            } else {
                str = "转出资金";
                url = STATIC_URL.domian+'/dsp/admin/agencyfinance/withdraw';
            }
            layer.confirm('是否确定'+str+'？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                var data = {
                    'agenID': $scope.advertiserID,//广告主ID
                    'money': $scope.money,
                };
                proxy.proxy({
                    url: url,
                    load: true,
                    data: {
                        data:data
                    },
                    success: function(){
                        layer.closeAll();
                        layer.msg(str+"成功")
                        getList($("#pageToolbar .focus").html());
                    }
                })
            });
        }
        // 修改广告公司状态
        $scope.setStatus = function (item) {
            var adv = {
                id: item.id,
                state: item.open?"10":"20"
            }
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/advertiser/modify',
                load:true,
                data: {
                    data:adv
                },
                success:function(){
                    item.state = item.state == "10"?"20":"10";
                },
                error: function () {
                    // 失败时,将switch状态重置
                    item.open = !item.open
                }
            })
        }
        // 修改溢价策略
        // $scope.setFixe = function (item) {
        //     item.fixedPrice = item.fixedPrice == "N" ? "Y":"N";
        // }
        $scope.checkDirect = function(item){
            if(item == "1") {
                $scope.agent.advanceProfit = "N";
            }
        }
        $scope.checkMode = function(){}
        // 切换溢价策略
        $scope.changeMode = function(item) {
            var str = item.fixedPrice == 'N'? '目前使用的溢价策略是“出价回推”模式；<br/>是否确认切换为“固定出价”模式？':'目前使用的溢价策略是“固定出价”模式；<br/>是否确认切换为“出价回推”模式？';
            layer.confirm(str, {
                btn: ['确定','取消'] //按钮
            }, function(){
                var adv = {
                    id: item.id,
                    fixedPrice: item.fixedPrice == "Y"?"N":"Y"
                }
                proxy.proxy({
                    url: STATIC_URL.domian+'/dsp/advertiser/modify',
                    load:true,
                    data: {
                        data:adv
                    },
                    success:function(){
                        item.fixedPrice = adv.fixedPrice;
                        layer.closeAll();
                        layer.msg("成功")
                    }
                })
            });
            
        }

        // 显示修改广告公司密码弹框
        $scope.showRePwd = function(id) {
            $scope.pwd.id = id;
            layer.open({
                type: 1,
                title: "重置密码",
                content: $('.rePwd'),
                area:["400px","280px"]
            })
        }

        // 重置广告主密码
        $scope.resetAdvPWD = function() {
            var pwd = $scope.pwd;
            if(pwd.passWord != pwd.passWord2) return layer.msg("两次密码不一致!");
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/reset/adv/passwd',
                load:true,
                data: {
                    id: pwd.id,
                    newPasswd: pwd.passWord
                },
                success: function(){
                    layer.closeAll();
                    layer.msg("修改成功!");

                }
            })
        }

        // 显示修改广告公司弹框
        $scope.showAgent = function(agent) {
            $scope.agent = {
                id: agent.id,
                name: agent.name,
                address: agent.address,
                contacts: agent.contacts,
                telephone: agent.telephone,
                advanceProfit: agent.advanceProfit,
                isDirect: agent.isDirect,
                fixedPrice: agent.fixedPrice,
                premium: (agent.premium * 100).toFixed(2),
                title: "编辑广告公司",
            }

            $("#agentModal").modal()
        }

        $scope.showOEM = function(item){
            $scope.orgID = item.id;
            // 查询OEM信息
            proxy.proxy({
                'url': STATIC_URL.domian+'/dsp/user/oem/query/agency',
                'load':true,
                'data': {
                    data:item.id
                },
                success: function (res) {
                    $scope.oemList = res.data;
                    if($scope.oemList.length == 0) $scope.oemList.push({url:""})
                    var data = $scope.oemList;
                    $scope.oem = {
                        background: data[0].background || "",// 登陆页面背景图片
                        loginLogo: data[0].loginLogo || "",//登陆页面Logo地址
                        staticLogo: data[0].staticLogo || "",//导航栏Logo地址
                        sdkLogo: data[0].sdkLogo || "",//SDK Logo地址
                        iconUrl: data[0].iconUrl || "",//角标图片地址
                        title: data[0].title || "",//所有oem文字信息
                        copyright: data[0].copyright || "",//版权信息
                        adLogo: data[0].adLogo || "",
                        adLogoExt: data[0].adLogoExt || "",
                        adLogoUrl: data[0].adLogoUrl || "",
                        adLabel: data[0].adLabel || ""
                    }
                    $("#oemModal").modal();
                }
            });
        }

        // 显示新建广告公司弹框
        $scope.newAgent = function() {
            $scope.agent = {
                "type": "2",
                "isDirect": "0",
                "advanceProfit": "N",
                "fixedPrice": "N",
                "title": "新建广告公司"
            }
            $("#agentModal").modal();

        }

        // 添加/编辑广告公司
        $scope.addAgent = function() {
            var agent = angular.copy($scope.agent),
                premium = agent.premium,
                phoneReg = /^1\d{10}$/;
            agent.type = "2";
            agent.roleID = "1";
            if(agent.passWord != agent.passWord2) return layer.msg("两次密码不相同!");
            if(!phoneReg.test(agent.telephone)) return layer.msg("手机号码格式有误!");
            if(!agent.id) {
                if(!agent.loginName) return layer.msg("请输入账户名称!");
                if(!agent.passWord) return layer.msg("请输入密码!");
            }
            if(agent.advanceProfit == 'Y') agent.fixedPrice = undefined; // 预提利润模式没有策略
            if(agent.isDirect == 1) agent.advanceProfit = undefined; // 直客没有溢价模式
            // 判断是否有溢价编辑权限
            if($scope.permission.act['代理商管理'] && $scope.permission.act['代理商管理'].sub['代理商溢价设置']) {
                if(premium == "" || isNaN(premium) || premium < 0) return layer.msg("利润必须为大于等于0的数字！")
                if(premium > $scope.premiumMax*100) return layer.msg("利润设置不能超过"+($scope.premiumMax*100)+"%")

                agent.premium = premium/100+"";
            }
            // var data = angular.copy(agent);
            agent.open = undefined;
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/advertiser/' + (agent.id?"modify":"add"), // id存在修改  不存在添加
                load:true,
                data: {
                    data: agent
                },
                success: function(){
                    layer.msg("操作成功!");
                    $("#agentModal").modal("hide");
                    getList();
                }
            })
        }
        $scope.addUrl = function() {
            $scope.oemList.push({url:""});
        }
        $scope.removeUrl = function(index) {
            $scope.oemList.splice(index,1);
        }

        $('[data-toggle="tooltip"]').tooltip()
        //提示信息显示
        $scope.tips = function (event,str) {
            layer.tips(str, $(event.target), {
                time: 0,
                tips: [1, '#fffee3']
            });
        }
        $('.icon-help').mouseleave(function(){
            layer.closeAll();
        })
        getList();
        getPremiumMax();
        getProfit();


        function getList(current, pagesize) {
            var data = {
                'page': (current || $('.ui-pager.focus').html() || 1)+"",
                'size': (pagesize || 20)+"",
                'filter': $scope.filter,
                "sort": ["cTime,1"],
                sTime : $scope.sTime+" 00:00:00",
                eTime : $scope.eTime+" 23:59:59"
            };
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/agency/list',
                data: data,
                success: function(res){
                    // 获得列表
                    $scope.list = res.data.data;

                    $("#pageToolbar").html("");
                    $('#pageToolbar').Paging({
                        pagesize: pagesize || '20',
                        current: current || $('.ui-pager.focus').html() || '1',
                        count:res.data.total,
                        toolbar:true,
                        'hash': false,
                        callback:getList
                    });
                }
            })
        }

        $scope.saveOEM = function () {
            var oemInfos = [];
            var urlFlag = true;
            var reg = /^(https?:\/\/)|(\/)/;
            // 重组oemInfos数据
            $scope.oemList.forEach(function(v,i){
                if(v.url) {
                    var obj = angular.copy($scope.oem)
                    if(v.url.match(reg))  return urlFlag = false
                    obj.url = v.url;
                    obj.orgID = $scope.orgID;
                    oemInfos.push(obj)
                }
            })
            if(!urlFlag) {
                return layer.msg("域名格式错误，禁止输入协议（http/https），禁止输入特殊字符（/）")
            }
            if(oemInfos.length == 0) return layer.msg("请输入自有域名！")
            // 将重组好的数据替换
            $scope.oemList.oemInfos = oemInfos;
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/user/oem/modify/agency',
                load: true,
                data: {
                    data: {
                        orgID: $scope.orgID,
                        oemInfos: oemInfos
                    }
                },
                success: function(){
                    layer.msg("修改成功");
                    $("#oemModal").modal('hide')
                }
            })
        }
        
        $scope.uploadImg = function (obj) {
            $scope.imgObj = obj;
            $("#upload").trigger("click");
        }
        function getPremiumMax () {
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/sys/parameter/query',
                load: true,
                data: {
                    "filter":{"feature":"dsp.feature.saasdsp.agency.profix.maxvalue"}
                },
                success: function(res){
                    $scope.premiumMax = res.data[0].value*1 || 0.8;
                }
            })
        }
        function getProfit () {
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/sys/parameter/query',
                load: true,
                data: {
                    "filter":{"feature":"dsp.feature.agency.advance.allow"}
                },
                success: function(res){
                    $scope.profitType = res.data[0].value;
                }
            })
        }

        // 上传文件按钮
        fileUpload({
            'btnId': "upload",
            'funcUrl': '1',
            'FileUploaded':function(info){
                $scope.$apply(function(){
                    $scope.oem[$scope.imgObj.attr] = info.url;
                })
            },
            'BeforeUpload': function (up, file, next) {
                var nFile = file.getNative(),
                    image = new Image(),
                    size = $scope.imgObj.size,
                    width = $scope.imgObj.width,
                    height = $scope.imgObj.height;
    
                // 判断文件类型
                if($scope.imgObj.fileType != 'all') {
                    if (!(/.png$/i).test(file.name)){
                        up.removeFile(file);
                        return layer.msg("格式错误，请上传png格式。")
                    }
                }

                // 判断文件大小
                if(nFile.size >= size*1024) {
                    up.removeFile(file);
                    return layer.msg("文件不得大于"+size+"K")
                }

                if(width && height) {
                    //加载图片获取图片真实宽度和高度
                    image.onload= function() {
                        // 多种尺寸
                        if(typeof width == 'object') {
                            var flag = false;
                            for(var i = 0; i < width.length; i ++) {
                               // 判断图片比例
                                if(image.width == width[i] && image.height == height[i]){
                                    flag = true;
                                    break;
                                }
                            }
                            if(flag) {
                                next();
                            } else {
                                up.removeFile(file);
                                layer.msg("图片的尺寸不规范，请重新上传！")
                            }
                        } else { // 单种尺寸
                            // 判断图片比例
                            if(image.width != width || image.height != height){
                                up.removeFile(file);
                                layer.msg("图片的尺寸不是"+width+"x"+height+"，请重新上传！")
                            } else {
                                next();
                            }
                        }
                    };
                } else {
                    next();
                }
    
                image.src = window.URL.createObjectURL(nFile);
            }
        })

        $('#oemModal').on('shown.bs.modal', function (e) {
            // 关键代码，如没将modal设置为 block，则$modala_dialog.height() 为零
            $(this).css('display', 'block');
            var modalHeight=$(window).height() / 2 - $(this).find('.modal-dialog').height() / 2;
            $(this).find('.modal-dialog').css({
                'margin-top': modalHeight
            });
        });

    })
})();